<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 量化任务
 * @author Cuil <lntschampion@163.com>
 * @date 2017-12-22
 */
class Quantification extends MY_Controller{
    public function __construct()
    {
        parent::__construct();
//        $this->load->model('M_quantification_User');
//        $this->load->model('M_sendsub');
        $this->load->model('M_quantification_User');
    }

    public function index()
    {
        if ($this->input->get_post("inajax")) {
            $this->ajax_lists();
        }
        $this->load->view('quantitative');
    }

    //ajax page list
    function ajax_lists()
    {
        $this->load->model('M_quantification_User');
        $page = getParam($this->input->get_post("page"), 'int', 1);
        $type = getParam($this->input->get_post("type"), 'string');
        $nian = getParam($this->input->get_post("nian"), 'string');
        $yue  = getParam($this->input->get_post('yue'),'string');
        $name = getParam($this->input->get_post('name'),'string');
        $quant_name = getParam($this->input->get_post('quant_name'),'string');
        $per_page = 15;

        //统计图
        //查询排除的统计
        $sql = "select Id from t_auth_roles where RoleName like '%普通%' or RoleName like '%管理员%'";
        $in_li = $this->M_quantification_User->querylist($sql);
        $not_in = '0,0';
        if(!empty($in_li)){
            foreach($in_li as $k=>$v){
                $not_in .= ','.$v['Id'];
            }
        }

        //查询柱状图的数据
        $tables = array('bjnz_new_quantification_user_map'=>'q','t_auth_multiple'=>'m','t_auth_roles'=>'r');
        $join = array('q.PID = m.UserID','m.RoleId = r.Id');
        $where = 'q.isdel = 1 AND q.type = 1 AND m.RoleId NOT in ('.$not_in.')';
        $where_1 = '';
        if(!empty($nian)) {
            $where_1 .= " AND FROM_UNIXTIME(q.start_time,'%Y') = ".$nian;
            }
        if($type == 'month' && !empty($yue)){ //月
            $where_1 .= " AND FROM_UNIXTIME(q.start_time,'%m') =".$yue;
        }
        if($type == 'quarter' && !empty($yue)){ //季度
            $where_1 .= " AND quarter( FROM_UNIXTIME(q.start_time ) ) = ".$yue;
        }
        $where = $where.$where_1;
        //角色
        $auth_list = $this->M_quantification_User->getJoinList($tables,$join,'q.*,m.RoleId,r.RoleName',$where,null,null,'q.id desc','m.RoleId');
        //完成量
        $wancheng = array();
        //接单量
        $jiedan = array();
        $juese = array();
        if(!empty($auth_list)){
            foreach($auth_list as $k=>$v){
               // $v['RoleId']  角色id
                $juese[] = $v['RoleName'];
                $where_w = 'm.RoleId = '.$v['RoleId'] .' AND q.status = 2 AND q.isdel = 1';
                $where_w = $where_w.$where_1;
                $wancheng[] = $this->M_quantification_User->getJoinOne($tables,$join,'count(*)',$where_w);
                $where_j = $where_w = 'm.RoleId = '.$v['RoleId'] .' AND q.isdel = 1';
                $where_j = $where_j.$where_1;
                $jiedan[] = $this->M_quantification_User->getJoinOne($tables,$join,'count(*)',$where_j);
            }
        }

        //列表
        $limit 	 = ($page-1)*$per_page;
        //查询详细信息的时候1
        if(!empty($name)){
            $sql = "select Id from t_auth_roles where RoleName like '%".$name."%'";
            $in_li = $this->M_quantification_User->querylist($sql);
            if($in_li){
                $where.= ' AND RoleId = '.$in_li[0]['Id'];
            }
//            $limit = 0;
//            $per_page = 1000;
        }
        if(!empty($quant_name))
        {
            $where .=" AND u.user_name like '%$quant_name%'";
        }
        $tables = array('bjnz_new_quantification_user_map'=>'q','t_auth_multiple'=>'m','t_auth_roles'=>'r','t_user'=>'u','t_enterprise_dept'=>'ed');
        $join = array('q.PID = m.UserID','m.RoleId = r.Id','q.PID = u.user_id','u.department_id = ed.ID');

        $list = $this->M_quantification_User->getJoinList($tables,$join,'count(q.PID) as rw,count(IF(q.status=2,1,null)) as wwc,count(distinct(q.map_id)) as mapnum,count(DISTINCT(IF(q.end_number>0,q.map_id,NULL))) as num,q.*,m.RoleId,r.RoleName,ed.Name,u.LoginName,u.user_name',$where,$per_page,$limit,'q.id desc','q.PID' );
        foreach($list as $k=>&$v){
            $v['PID'] = empty($v['PID']) ? '' : $v['PID'];
            $v['UserName'] = empty($v['UserName']) ? '' : $v['UserName'];
            $v['RoleName'] = empty($v['RoleName']) ? '' : $v['RoleName'];
            $v['Name'] = empty($v['Name']) ? '' : $v['Name'];
            $v['LoginName'] = empty($v['LoginName']) ? '' : $v['LoginName'];
            $v['rw'] = empty($v['rw']) ? 0 : $v['rw'];
            $v['wwc'] = empty($v['wwc']) ? 0 : $v['wwc'];
        }
        $total = $this->M_quantification_User->getJoinOne($tables,$join,'count(DISTINCT q.PID)',$where);
        $this->load->library("common_page");
        $page_string = $this->common_page->page_string($total, $per_page, $page);
        $data = array(
           'data'=>array(
               'name'=>$juese,
               'taskSum'=>$jiedan,
               'completeNum'=>$wancheng,
           ),
            'list'=>$list,
        );
        exit(result_to_towf_new($data, 1, '成功', $page_string));
    }
    //干部网格巡视情况（统计图）
    function get_leader()
    {
        $page = getParam($this->input->get_post("page"), 'int', 1);
        $dept_id = getParam($this->input->get_post("dept_id"), 'int', 0);//获取顶级分类ID
//            $dept_id=42;
        $year = getParam($this->input->get_post("year"), 'string');
        $month  = getParam($this->input->get_post('month'),'string');
//            $date = getParam($this->input->get_post("time"), 'string', "");//获取查询月，默认当前月
        $name = getParam($this->input->get_post('name'), 'string');
//            $name='王朝辉';
//        $dept_id=1;
//        $month='12';
//        $year='2017';
        $where = "";
//            if (empty($date)) {
//                $year = date('Y', $time);
//                $month = date('m', $time);
//            } else {
//                $time = strtotime($date);
//                $year = date('Y', $time);
//                $month = date('m', $time);
//            }
//            $year = "2017";
//            $month = "7";
        if (!empty($year)) {
            $where .= " AND FROM_UNIXTIME(um.start_time,'%Y') = " . $year;
        }
        if (!empty($month)) { //月
            $where .= " AND FROM_UNIXTIME(um.start_time,'%m') =" . $month;
        }
        $limit='';
        if (!empty($name)) {
            $where .= " AND u.user_name ='" . $name . "'";
            $per_page = 15;
            $total = $this->M_quantification_User->get_leader("", $where, 1,'', 1);
            $total = $total[0]['count'];
            $this->load->library("common_page");
            $page_string = $this->common_page->page_string($total, $per_page, $page);
            $limit = " limit ".($page - 1) * $per_page;
            $limit .= ",{$per_page}";
            $list = $this->M_quantification_User->get_leader("", $where, 1,$limit);//
            $data1 = $list;
            foreach ($data1 as $k=>$v) {
                $data1[$k]['start_time'] = date('Y-m-d H:i:s', $v['start_time']);
                $data1[$k]['end_time'] = date('Y-m-d H:i:s', $v['end_time']);
                $data1[$k]['addtime'] = empty($v['addtime'])?"":date('Y-m-d H:i:s', $v['addtime']);
            }
            exit(result_to_towf_new($data1, 1, '成功', $page_string));
        }
        else
        {
            $tree = $this->M_quantification_User->getChildrenIds($dept_id);//获取所有分类id
            $list = $this->M_quantification_User->get_leader($tree, $where, 0,$limit);//
            if(empty($list))
            {
                $data1='';
            }
            else
            {
                foreach ($list as $value) {
                    $data1['UserName'][] = $value['user_name'];
                    $data1['num'][] = $value['num'];
                    $data1['wnum'][] = $value['wnum'];
                }
            }
        }
        //要求：干部量化任务（按月的考核方式）
        $data['data']=$data1;
        $data['code']="0";
        $data['info']="ok";
        $json_string = json_encode($data);
        exit($json_string);
    }
    //干部网格巡视情况（表格）
    function get_leadertable()
    {
        $page = getParam($this->input->get_post("page"), 'int', 1);//页码
        $per_page = getParam($this->input->get_post("count"), 'int', 10);//页码
        $dept_id = getParam($this->input->get_post("dept_id"), 'int', 0);//获取分类ID
        $year = getParam($this->input->get_post("year"), 'string');//年
        $month  = getParam($this->input->get_post('month'),'string');//月
        $pid = getParam($this->input->get_post('pid'), 'int',0);//详情必须字段，标识：传如PID
        $status = getParam($this->input->get_post('status'), 'int',0);//状态 0全部 1未完成 2完成
        $tree = $this->M_quantification_User->getChildrenIds($dept_id);//获取分类id
        $where = '';
//        $dept_id=1;
//        $month='12';
//        $year='2017';
        if($status!=0)
        {
            $where .= " AND um.status=$status ";
        }
        if($dept_id!=0)
        {
            $where .= " AND u.department_id in($tree) ";
        }
        if($pid!=0)
        {
            $where .= " AND u.user_id=$pid ";
        }
        if (!empty($year)) {
            $where .= " AND FROM_UNIXTIME(um.start_time,'%Y') = " . $year;
        }
        if (!empty($month)) { //月
            $where .= " AND FROM_UNIXTIME(um.start_time,'%m') =" . $month;
        }
        if($pid!=0)
        {
            $total = $this->M_quantification_User->get_leader("", $where, 1,'', 1);
        }
        else
        {
            $total = $this->M_quantification_User->get_leader("", $where, 1,'', 3);
        }
        $total = $total[0]['count'];
        $this->load->library("common_page");
        $page_string = $this->common_page->page_string($total, $per_page, $page);
        $limit = " limit ".($page - 1) * $per_page;
        $limit .= ",{$per_page}";
        if($pid!=0)
        {
            $list = $this->M_quantification_User->get_leader("", $where, 1,$limit,0);//
            foreach ($list as $k=>$v) {
                $list[$k]['start_time'] = date('Y-m-d H:i:s', $v['start_time']);
                $list[$k]['end_time'] = date('Y-m-d H:i:s', $v['end_time']);
                $list[$k]['addtime'] = empty($v['addtime'])?"":date('Y-m-d H:i:s', $v['addtime']);
            }
        }
        else
        {
            $list = $this->M_quantification_User->get_leader("", $where, 1,$limit,2);
        }
        $data1 = $list;
        exit(result_to_towf_new($data1, 1, '成功', $page_string));
    }
    //导出干部网格巡视
    function export_leader()
    {
        $dept_id = getParam($this->input->get_post("dept_id"), 'int', 0);//获取分类ID
        $year = getParam($this->input->get_post("year"), 'string');//年
        $month  = getParam($this->input->get_post('month'),'string');//月
        $status = getParam($this->input->get_post('status'), 'int',0);//状态 0全部 1未完成 2完成
//        $dept_id=1;
//        $month='12';
//        $year='2017';
        $tree = $this->M_quantification_User->getChildrenIds($dept_id);//获取分类id
        $where = '';
        if($status!=0)
        {
            $where .= " AND um.status=$status ";
        }
        if($dept_id!=0)
        {
            $where .= " AND u.department_id in($tree) ";
        }
        if (!empty($year)) {
            $where .= " AND FROM_UNIXTIME(um.start_time,'%Y') = " . $year;
        }
        if (!empty($month)) { //月
            $where .= " AND FROM_UNIXTIME(um.start_time,'%m') =" . $month;
        }
        $list = $this->M_quantification_User->get_leader("", $where, 1,'',2);
        //读取excel模板
        set_include_path(get_include_path() . PATH_SEPARATOR . APPPATH . 'libraries');
        ini_set('include_path', ini_get('include_path').PATH_SEPARATOR.APPPATH.'libraries/');

        require_once 'PHPExcel.php';
        include_once APPPATH.'libraries/PHPExcel/IOFactory.php';

        $objPHPExcel = new PHPExcel();
        $account_name =date("Y").date("m").date("d").date("H").date("i").date("s");
        $objPHPExcel->getProperties()->setCreator("ids5")
            ->setLastModifiedBy("ids5")
            ->setTitle($account_name."_干部网格巡视统计导出信息")
            ->setSubject($account_name."_干部网格巡视统计导出信息")
            ->setDescription($account_name."_干部网格巡视统计导出信息")
            ->setKeywords("office 2007 openxml php")
            ->setCategory($account_name."_干部网格巡视统计导出信息");
        //名称
        $excel_arr = array('A'=>'工号',
            'B'=>'姓名',
            'C'=>'部门',
            'D'=>'量化任务数',
            'E'=>'已巡视网格次数',
            'F'=>'未巡视网格次数'
            );
        foreach ($excel_arr as $key => $val){
            $objPHPExcel->setActiveSheetIndex()->setCellValue($key.'1',$val);
        }

        //宽度
        $objPHPExcel->getActiveSheet()->setTitle('干部网格巡视统计导出信息');
        $excel_len = array('A'=>'20','B'=>'15','C'=>'15','D'=>'15','E'=>'15','F'=>'15');
        foreach ($excel_len as $keys =>$vals){
            $objPHPExcel->getActiveSheet()->getColumnDimension($keys)->setWidth($vals);
        }
        $data= array();
        $num = 1;
//        foreach ($detail_list as $value)
//        {
//            $where1 = $where . " and um.grid_id = $value[id]";
//            $detail_list =  $this->M_quantification_User->get_wangge($start_time,$end_time,$where1,$limit,$type,0,$status);
//            $data[]=$detail_list;

        foreach($list as $aval){
//                $aval['start_time'] = empty($aval['start_time'])?"":date('Y-m-d H:i:s', $aval['start_time']);
//                $aval['end_time'] = empty($aval['end_time'])?"":date('Y-m-d H:i:s', $aval['end_time']);
//                $aval['addtime'] = empty($aval['addtime'])?"":date('Y-m-d H:i:s', $aval['addtime']);
            $num++;
            $objPHPExcel->setActiveSheetIndex()->setCellValue('A'.$num,$aval['user_account'])
                ->setCellValue('B'.$num,$aval['user_name'])
                ->setCellValue('C'.$num,$aval['department_name'])
                ->setCellValue('D'.$num,$aval['sum_number'])
                ->setCellValue('E'.$num,$aval['sum_end_number'])
                ->setCellValue('F'.$num,$aval['sum_number']-$aval['sum_end_number']);
        }
//            $item['addtime'] = empty($item['addtime'])?"":date('Y-m-d H:i:s', $item['addtime']);
//        }

        $FileNames = mb_convert_encoding($account_name,'gb2312','UTF-8');
        $FileNames = $FileNames."_export_file";
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$FileNames.'.xls"');
        #header('Content-Disposition: attachment;filename="'.iconv('utf-8', 'gb2312', $account_name."_export_file").'.xls"');
        header('Cache-Control: max-age=0');

        $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
        ob_end_clean();//清空（擦除）缓冲区并关闭输出缓冲
        $objWriter->save('php://output');
        exit;
    }
    //职工网格巡视详情
    function get_worker()
    {
        $arr = $this->input->get_post("id_arr");//人名PID组
        $page 		= getParam($this->input->get_post("page"),'int',1);
        $name = getParam($this->input->get_post('name'),'string');
//            $arr=array(2613,2646,3766);
        $starttime = $this->input->get_post("start_time");//ajax
        $endtime = $this->input->get_post("end_time");//ajax
//        $starttime = '2017-01-22';
//        $endtime = '2017-12-22';
//        $name = '策宝宝';
//        $arr[0] = '1';
        $start_time = strtotime($starttime);
        $end_time = strtotime(date('Y-m-d 23:59:59', strtotime($endtime)));
        $per_page=15;
        $where = '';
        $type=0;
        if($arr!=null)
        {
            if(count($arr)>1)
            {
                foreach($arr as $key=>$value) {
                    if ($value == "") {
                        unset($arr[$key]);
                    }
                }
                $arr = implode ( ',', $arr );
            }
            else
            {
                if(!empty($arr[0]))
                {
                    $arr = $arr[0];
                }
                else
                {

                    $dept = $this->M_quantification_User->getChildrenIds(214,1);//默认客运甲班
//                    $dept1 = $this->M_quantification_User->getChildrenIds(215);//默认客运甲班
//                    $dept2 = $this->M_quantification_User->getChildrenIds(216);//默认客运甲班
//                    $dept3 = $this->M_quantification_User->getChildrenIds(217);//默认客运甲班
                    $arr = $this->M_quantification_User->get_pid($dept);
//                    $arr1 = $this->M_quantification_User->get_pid($dept1);
//                    $arr2 = $this->M_quantification_User->get_pid($dept2);
//                    $arr3 = $this->M_quantification_User->get_pid($dept3);
                    $arr = $this->rebuild_array($arr);//多维数组变一维数组
//                    $arr1 = $this->rebuild_array($arr1);//多维数组变一维数组
//                    $arr2 = $this->rebuild_array($arr2);//多维数组变一维数组
//                    $arr3 = $this->rebuild_array($arr3);//多维数组变一维数组
                    $arr = array_merge($arr);
//                    $arr = array_merge($arr,$arr1,$arr2,$arr3);
                    $arr = implode ( ',', $arr );//默认
                }
            }
        }
        else
        {

            $dept = $this->M_quantification_User->getChildrenIds(214,1);//默认客运甲班
//                    $dept1 = $this->M_quantification_User->getChildrenIds(215);//默认客运甲班
//                    $dept2 = $this->M_quantification_User->getChildrenIds(216);//默认客运甲班
//                    $dept3 = $this->M_quantification_User->getChildrenIds(217);//默认客运甲班
            $arr = $this->M_quantification_User->get_pid($dept);
//                    $arr1 = $this->M_quantification_User->get_pid($dept1);
//                    $arr2 = $this->M_quantification_User->get_pid($dept2);
//                    $arr3 = $this->M_quantification_User->get_pid($dept3);
            $arr = $this->rebuild_array($arr);//多维数组变一维数组
//                    $arr1 = $this->rebuild_array($arr1);//多维数组变一维数组
//                    $arr2 = $this->rebuild_array($arr2);//多维数组变一维数组
//                    $arr3 = $this->rebuild_array($arr3);//多维数组变一维数组
            $arr = array_merge($arr);
//                    $arr = array_merge($arr,$arr1,$arr2,$arr3);
            $arr = implode ( ',', $arr );//默认
        }
//        else
//        {$dept = $this->M_quantification_User->getChildrenIds(214);//默认客运甲班
//            $dept1 = $this->M_quantification_User->getChildrenIds(215);//默认客运甲班
//            $dept2 = $this->M_quantification_User->getChildrenIds(216);//默认客运甲班
//            $dept3 = $this->M_quantification_User->getChildrenIds(217);//默认客运甲班
//            $arr = $this->M_quantification_User->get_pid($dept);
//            $arr1 = $this->M_quantification_User->get_pid($dept1);
//            $arr2 = $this->M_quantification_User->get_pid($dept2);
//            $arr3 = $this->M_quantification_User->get_pid($dept3);
//            $arr = $this->rebuild_array($arr);//多维数组变一维数组
//            $arr1 = $this->rebuild_array($arr1);//多维数组变一维数组
//            $arr2 = $this->rebuild_array($arr2);//多维数组变一维数组
//            $arr3 = $this->rebuild_array($arr3);//多维数组变一维数组
//            $arr = array_merge($arr,$arr1,$arr2,$arr3);
//            $arr = implode ( ',', $arr );//默认
//        }
//        $arr= '69,8,10,41,42,1,50,63,67,68,11,12,13,14,36,37,44,2,3,38,39,52,65,70,47,46,51,9,53,55,54,43,66,58,57,59,60,61,62,64,56,71,74,77,78,79,73,76,80,72,75,81,82';
        $limit = '';
//            $where .= " AND ((  um.start_time <= $start_time AND um.end_time >= $start_time  ) OR (  um.start_time <= $end_time AND um.end_time >= $end_time  ) OR (  um.start_time >= $start_time AND um.end_time <= $end_time  ))";
        $where .= " AND um.start_time >= $start_time AND um.start_time < $end_time ";

        if(!empty($name)){
            $where .= " AND u.user_name ='".$name."'";
            $type=1;
            $total  	= $this->M_quantification_User->get_worker($start_time,$end_time,$where,$type,'',1);
            $total = $total[0]['count'];
            $this->load->library("common_page");
            $page_string = $this->common_page->page_string($total, $per_page, $page);
            $limit 	 = " limit ".($page-1)*$per_page;
            $limit	.=",{$per_page}";
        }
        else
        {
            $where .= " AND u.user_id in($arr) ";
        }
        $res =  $this->M_quantification_User->get_worker($start_time,$end_time,$where,$type,$limit);
        $data1='';
//
        if(empty($name))
        {
            foreach($res as $value)
            {
                $data1['UserName'][] = $value['user_name'];
                $data1['num'][] = $value['num'];
                $data1['wnum'][] = $value['wnum'];
            }
        }
        else
        {
            $data1 = $res;
            foreach ($data1 as &$item) {
                $item['start_time'] = date('Y-m-d H:i:s', $item['start_time']);
                $item['end_time'] = date('Y-m-d H:i:s', $item['end_time']);
                $item['addtime'] = empty($item['addtime'])?"":date('Y-m-d H:i:s', $item['addtime']);
                if($item['finish_number'] == 0)
                {
                    $item['status'] = '未巡视';
                }
                elseif($item['finish_number'] == $item['number'])
                {
                    $item['status'] = '已完成任务';
                }
                else
                {
                    $item['status'] = '已巡视';
                }
            }
        }
        if(!empty($name)){
            exit(result_to_towf_new($data1, 1, '成功', $page_string));
        }
        $data['data']=$data1;
        $data['code']="0";
        $data['info']="ok";
        $json_string = json_encode($data);
        exit($json_string);
    }
    //网格巡视情况统计
    function get_assign()
    {
        //当前默认只查询24小时内的任务，24小时内 2小时任务只有11个。
        $page 		= getParam($this->input->get_post("page"),'int',1);
        $detail 		= getParam($this->input->get_post("detail"),'int',0);//$detail :1 查看详情
        $status 		= getParam($this->input->get_post("status"),'int',0);//$status :0 全部 1 未完成 2 已完成 状态码
        $hours 		= getParam($this->input->get_post("hours"),'int',0);//$hours :2小时 6小时 8小时 状态码
//            $seach_time 		= getParam($this->input->get_post("search_time"),'int',0);//时段查询
//            $status=0;
        $starttime = $this->input->get_post("start_time");//ajax
        $endtime = $this->input->get_post("end_time");//ajax
//        $starttime = '2017-11-22 11:00';
//        $endtime = '2017-12-22 11:00';
//        $hours=2;
        $start_time = strtotime($starttime);
        $end_time = strtotime($endtime);
        $map_id = getParam($this->input->get_post("map_id"), 'string', "");//获取查询月，默认当前月
//        $map_id=9;
//        $detail=2;
//        $status=1;

//            $seach_time=1;
//            $map_id=2;


        $where='';
        $statu='';
        $type=0;
        $per_page=15;
        $limit='';
        if(!empty($map_id) && $detail == 1)
        {
            $type=1;
            $where .= " and um.grid_id = $map_id";
            $total  	= $this->M_quantification_User->get_wangge($start_time,$end_time,$where,'',$type,1,$status,$hours);
            $total = $total[0]['count'];
            $this->load->library("common_page");
            $page_string = $this->common_page->page_string($total, $per_page, $page);
            $limit 	 = " limit ".($page-1)*$per_page;
            $limit	.=",{$per_page}";
        }
        elseif(!empty($map_id))
        {
            $where .= " where grid_id = $map_id";

            if($detail == 2)
            {
                $where = " AND map.grid_id = $map_id";
                $type=2;
                $arr = array();
                $key =0;
                //时段查询
                $list =  $this->M_quantification_User->get_wangge($start_time,$end_time,$where,$limit,$type,0,$status,$hours);
                foreach($list as $value)
                {
                    $arr[$value['start_time']]['num'] =$value['num'];
                    $name = empty($name) ? $value['grid_name'] : $name;
                }
                $list=array();
                $start = date('H',$start_time);
                $n = 24/$hours;
                $n1 = ceil(($start-1)/$hours);
                $start = $n1*$hours+1;
                if($start>24)
                {
                    $start = $start-24;
                    $start_time = $start_time+86400;//超出12小时加1天
                }
                $start = strtotime(date("Y-m-d $start:i:s",$start_time));//第一个任务的开始时间
                while($start<$end_time)
                {
                    if(array_key_exists($start,$arr))
                    {
                        $numb = $arr["$start"]['num'];
                        if($numb==0)
                        {
                            $t = 1;//未巡视
                            $sta = "未巡视";
//                                echo "接了任务没去巡视$numb";
                        }
                        else
                        {
                            $t = 2;//已巡视
                            $sta = "已巡视";
//                                echo "接了任务去巡视过了$numb";
                        }
                    }
                    else
                    {
                        $t = 1;//暂无任务
                        $sta = "暂无任务";
//                            echo "没有人接任务";
                    }
                    $dd = date("H",$start);
                    if($status == 0)
                    {
                        $list[$key]['start_time'] = date('Y-m-d H:i:s', $start);
                        $list[$key]['grid_name'] = $name;
                        if($dd == 01 && $hours==2)
                        {
                            $start = $start+3600*$hours*2;
                        }
                        else
                        {
                            $start = $start+3600*$hours;
                        }
                        $list[$key]['end_time'] = date('Y-m-d H:i:s', $start);
                        $list[$key]['status'] = $sta;
                    }
                    else
                    {
                        $list[$t][$key]['start_time'] = date('Y-m-d H:i:s', $start);
                        $list[$t][$key]['grid_name'] = $name;
                        if($dd == 01 && $hours==2)
                        {
                            $start = $start+3600*$hours*2;
                        }
                        else
                        {
                            $start = $start+3600*$hours;
                        }
                        $list[$t][$key]['end_time'] = date('Y-m-d H:i:s', $start);
                        $list[$t][$key]['status'] = $sta;
                    }
                    $key++;
                }
            }
        }
        if($status != 0 && $detail ==2)
        {
            $list = $list["$status"];
        }
        if($detail!=2)
        {
            $list =  $this->M_quantification_User->get_wangge($start_time,$end_time,$where,$limit,$type,0,$status,$hours);
        }
        else
        {
            $this->load->library("common_page");
            $page_string = $this->common_page->page_string(count($list), $per_page, $page);
            $list = array_slice($list,($page-1)*$per_page,$per_page);
        }
        $data1 = $list;
        if(!empty($map_id) && $detail ==1){
            foreach($data1 as &$item)
            {
                $item['start_time'] = empty($item['start_time'])?"":date('Y-m-d H:i:s', $item['start_time']);
                $item['end_time'] = empty($item['end_time'])?"":date('Y-m-d H:i:s', $item['end_time']);
                $item['addtime'] = empty($item['addtime'])?"":date('Y-m-d H:i:s', $item['addtime']);
            }
            exit(result_to_towf_new($data1, 1, '成功', $page_string));
        }
        if((!empty($map_id) && $detail ==2))
        {
            exit(result_to_towf_new($data1, 1, '成功', $page_string));
        }
        $data['data']=$data1;
        $data['code']="0";
        $data['info']="ok";
        $json_string = json_encode($data);
        exit($json_string);
    }

    //网格巡视情况统计导出详情
    function export_assign()
    {
        $status 		= getParam($this->input->get_post("status"),'int',0);//$status :0 全部 1 未完成 2 已完成 状态码
        $hours 		= getParam($this->input->get_post("hours"),'int',0);//$hours :2小时 6小时 8小时 状态码
        $starttime = $this->input->get_post("start_time");//ajax
        $endtime = $this->input->get_post("end_time");//ajax
        $start_time = strtotime($starttime);
        $end_time = strtotime($endtime);
        $map_id = getParam($this->input->get_post("map_id"), 'string', "");//获取查询月，默认当前月
        $where='';
        $statu='';
        $type=0;
        $limit='';
        if(!empty($map_id))
        {
            $where .= " where grid_id = $map_id";
        }
//        $detail_list =  $this->M_quantification_User->get_wangge($start_time,$end_time,$where,$limit,1,0,$status,$hours);
//        $list =         $this->M_quantification_User->get_wangge($start_time,$end_time,$where,$limit,$type,0,$status,$hours);
        $detail_list =  $this->M_quantification_User->get_wangge($start_time,$end_time,$where,$limit,$type,0,$status,$hours);
//var_dump($detail_list);exit;
//        $data1 =  $this->M_quantification_User->get_wangge($start_time,$end_time,$where,$limit,$type,0,$status);

        $type=1;
        //读取excel模板
        set_include_path(get_include_path() . PATH_SEPARATOR . APPPATH . 'libraries');
        ini_set('include_path', ini_get('include_path').PATH_SEPARATOR.APPPATH.'libraries/');

        require_once 'PHPExcel.php';
        include_once APPPATH.'libraries/PHPExcel/IOFactory.php';

        $objPHPExcel = new PHPExcel();
        $account_name =date("Y").date("m").date("d").date("H").date("i").date("s");
        $objPHPExcel->getProperties()->setCreator("ids5")
            ->setLastModifiedBy("ids5")
            ->setTitle($account_name."_网格巡视统计导出信息")
            ->setSubject($account_name."_网格巡视统计导出信息")
            ->setDescription($account_name."_网格巡视统计导出信息")
            ->setKeywords("office 2007 openxml php")
            ->setCategory($account_name."_网格巡视统计导出信息");
        //名称
        $excel_arr = array('A'=>'网格名称',
            'B'=>'负责部门',
            'C'=>'实际巡视次数',
            'D'=>'未完成次数',
            'E'=>'是否被巡视');
        foreach ($excel_arr as $key => $val){
            $objPHPExcel->setActiveSheetIndex()->setCellValue($key.'1',$val);
        }

        //宽度
        $objPHPExcel->getActiveSheet()->setTitle('网格巡视统计导出信息');
        $excel_len = array('A'=>'20','B'=>'15','C'=>'15','D'=>'15','E'=>'15');
        foreach ($excel_len as $keys =>$vals){
            $objPHPExcel->getActiveSheet()->getColumnDimension($keys)->setWidth($vals);
        }
        $data= array();
        $num = 1;
//        foreach ($detail_list as $value)
//        {
//            $where1 = $where . " and um.grid_id = $value[id]";
//            $detail_list =  $this->M_quantification_User->get_wangge($start_time,$end_time,$where1,$limit,$type,0,$status);
//            $data[]=$detail_list;

            foreach($detail_list as $aval){
//                $aval['start_time'] = empty($aval['start_time'])?"":date('Y-m-d H:i:s', $aval['start_time']);
//                $aval['end_time'] = empty($aval['end_time'])?"":date('Y-m-d H:i:s', $aval['end_time']);
//                $aval['addtime'] = empty($aval['addtime'])?"":date('Y-m-d H:i:s', $aval['addtime']);
                $num++;
                $objPHPExcel->setActiveSheetIndex()->setCellValue('A'.$num,$aval['grid_name'])
                    ->setCellValue('B'.$num,$aval['department_name'])
                    ->setCellValue('C'.$num,$aval['number'])
                    ->setCellValue('D'.$num,$aval['wwc'])
                    ->setCellValue('E'.$num,$aval['status']!=0?($aval['number']==0?'未巡视':($aval['number']!=0?'未全部':'已巡视')):'未巡视');
            }
//            $item['addtime'] = empty($item['addtime'])?"":date('Y-m-d H:i:s', $item['addtime']);
//        }

        $FileNames = mb_convert_encoding($account_name,'gb2312','UTF-8');
        $FileNames = $FileNames."_export_file";
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$FileNames.'.xls"');
        #header('Content-Disposition: attachment;filename="'.iconv('utf-8', 'gb2312', $account_name."_export_file").'.xls"');
        header('Cache-Control: max-age=0');

        $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
        ob_end_clean();//清空（擦除）缓冲区并关闭输出缓冲
        $objWriter->save('php://output');
        exit;
    }
    //获取所有网格
    function get_all_map()
    {
        $map = $this->M_quantification_User->get_all_map();
        array_unshift($map,array('id'=>'','area'=>'全部网格'));
        $data['data']=$map;
        $data['code']="0";
        $data['info']="ok";
        $json_string = json_encode($data);
        exit($json_string);
    }
    //获取量化任务详情
    function get_detail()
    {
//        $this->load->model('M_quantification_User');
        $page = getParam($this->input->get_post("page"), 'int', 1);
        $type = getParam($this->input->get_post("type"), 'string');
        $nian = getParam($this->input->get_post("nian"), 'string');
        $yue  = getParam($this->input->get_post('yue'),'string');
        $pid = getParam($this->input->get_post('pid'),'string');
        $per_page = 15;
        $tables = array('bjnz_new_quantification_user_map'=>'q','t_bjnz_map'=>'m','t_user'=>'u');
        $join = array('q.map_id = m.id','q.PID = u.user_id');
        $where = 'q.PID='.$pid;
        $where_1 = '';
        if(!empty($nian)) {
            $where_1 .= " AND FROM_UNIXTIME(q.start_time,'%Y') = ".$nian;
        }
        if($type == 'month' && !empty($yue)){ //月
            $where_1 .= " AND FROM_UNIXTIME(q.start_time,'%m') =".$yue;
        }
        if($type == 'quarter' && !empty($yue)){ //季度
            $where_1 .= " AND quarter( FROM_UNIXTIME(q.start_time ) ) = ".$yue;
        }
        $where = $where.$where_1;
        //列表
        $limit 	 = ($page-1)*$per_page;
        $list = $this->M_quantification_User->getJoinList($tables,$join,'u.user_name,q.PID,m.area,q.start_time,q.end_time,q.end_number,q.number,q.status',$where,$per_page,$limit,'(q.map_id+0) desc,(q.start_time+0) asc');

        if(!empty($list)){
            foreach($list as &$v){
                $v['start_time'] = date("Y-m-d H:i:s",$v['start_time']);
                $v['end_time'] = date("Y-m-d H:i:s",$v['end_time']);
                $v['status'] = $v['status'] == 1 ? '未完成':'完成';
            }
        }
        $total = $this->M_quantification_User->getJoinOne($tables,$join,'count(*)',$where);
        $this->load->library("common_page");
        $page_string = $this->common_page->page_string($total, $per_page, $page);
        $data = array(
            'data'=>array(
            ),
            'list'=>$list,
        );
        exit(result_to_towf_new($data, 1, '成功', $page_string));
    }

    //导出excel
    public function export(){
        $page = getParam($this->input->get_post("page"), 'int', 1);
        $type = getParam($this->input->get_post("type"), 'string');
        $nian = getParam($this->input->get_post("nian"), 'string');
        $yue  = getParam($this->input->get_post('yue'),'string');
        $quant_name = getParam($this->input->get_post('quant_name'),'string');
        $per_page = 10000; //每一页显示的数量
        $sql = "select Id from t_auth_roles where RoleName like '%普通%' or RoleName like '%管理员%'";
        $in_li = $this->M_quantification_User->querylist($sql);
        $not_in = '0,0';
        if(!empty($in_li)){
            foreach($in_li as $k=>$v){
                $not_in .= ','.$v['Id'];
            }
        }
        $where = 'q.isdel = 1 AND m.RoleId NOT in ('.$not_in.')';
        if(!empty($quant_name))
        {
            $where .=" AND u.user_name like '%$quant_name%'";
        }
        $where_1 = '';
        if(!empty($nian)) {
            $where_1 .= " AND FROM_UNIXTIME(q.start_time,'%Y') = ".$nian;
        }
        if($type == 'month' && !empty($yue)){ //月
            $where_1 .= " AND FROM_UNIXTIME(q.start_time,'%m') =".$yue;
        }
        if($type == 'quarter' && !empty($yue)){ //季度
            $where_1 .= " AND quarter( FROM_UNIXTIME(q.start_time ) ) = ".$yue;
        }
        $where = $where.$where_1;
        $tables = array('bjnz_new_quantification_user_map'=>'q','t_auth_multiple'=>'m','t_auth_roles'=>'r','t_user'=>'u','t_enterprise_dept'=>'ed');
        $join = array('q.PID = m.UserID','m.RoleId = r.Id','q.PID = u.user_id','u.department_id = ed.ID');


        $limit = ($page - 1) * $per_page;
        $list = $this->M_quantification_User->getJoinList($tables,$join,'count(q.PID) as rw,count(IF(q.status=2,1,null)) as wwc,count(distinct(q.map_id)) as mapnum,count(DISTINCT(IF(q.end_number>0,q.map_id,NULL))) as num,q.*,m.RoleId,r.RoleName,ed.Name,u.LoginName,u.user_name',$where,$per_page,$limit,'q.id desc','q.PID' );

//        $list = $this->M_quantification_User->getJoinList($tables,$join,'q.*,m.RoleId,r.RoleName,mp.area,ed.Name,u.LoginName,u.user_name',$where,$per_page,$limit,'q.id desc');
        $info = array();
        foreach($list as $k=>$v){
            $info[$k] = array(
                'LoginName'=>$v['LoginName'],
                'username'=>$v['UserName'],
                'rolename'=>$v['RoleName'],
                'name'=>$v['Name'],
                'rw'=>$v['rw'],
                'wwc'=>$v['wwc'],
                'mapnum'=>$v['mapnum'],
                'num'=>$v['num'],
            );
        }
        $title = array('LoginName'=>'工号','username'=>'姓名','rolename'=>'职位','name'=>'部门','mapnum'=>'任务网格数','num'=>'实际网格数','rw'=>'量化任务','wwc'=>'实际完成');
        $this->excel_export($title, $info, '量化任务');
    }
    public function rebuild_array($arr){
        //rebuild a array
      static $tmp=array();

      for($i=0; $i<count($arr); $i++){
        if(is_array($arr[$i]['user_id']))
        {
            $this->rebuild_array($arr[$i]['user_id']);
        }
        else
        {
            $tmp[]=$arr[$i]['user_id'];
        }
      }

    return $tmp;
    }

}